#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3014,SC3028 source=/dev/null

# make sure we have a secure umask
umask 0002

# source all data from /var/hm_mode
[[ -r /var/hm_mode ]] && . /var/hm_mode

# source in the network config
[[ -r /etc/config/netconfig ]] && . /etc/config/netconfig

# signal that we are about to setup the network
# connection using a slow blinking blue LED
if [[ -e /sys/class/leds/rpi_rf_mod:green/trigger ]]; then
  echo none >/sys/class/leds/rpi_rf_mod:green/trigger
  echo none >/sys/class/leds/rpi_rf_mod:red/trigger
  echo timer >/sys/class/leds/rpi_rf_mod:blue/trigger
  echo 499 >/sys/class/leds/rpi_rf_mod:blue/delay_on
  echo 499 >/sys/class/leds/rpi_rf_mod:blue/delay_off
fi

# we exit if if-up.d is called for "lo"
if [[ "${IFACE}" == "lo" ]]; then
  exit 0
fi

echo -n "${IFACE}:"

# only continue if this network interface exists
if [[ ! -L "/sys/class/net/${IFACE}" ]]; then
  echo -n " missing, "
  exit 1
fi

# only continue if another interface hasn't
# setup everything correctly already
if [[ -f /var/status/hasIP ]] &&
   [[ -f /var/status/hasLink ]]; then

  /sbin/ip link set "${IFACE}" down
  echo -n " disabled, "

  # make sure that the wifi power is disabled
  # if not required
  case "${IFACE}" in
    wlan*)
      /usr/sbin/iw dev "${IFACE}" set power_save on
      /usr/sbin/rfkill block wlan
    ;;
  esac
  exit 0
fi

# depending on the interface we have to either setup
# a ethernet interface or wifi
case "${IFACE}" in
  eth*)
    # wait until the link is up
    /sbin/ip link set "${IFACE}" up
    i=0
    while [[ "$(cat "/sys/class/net/${IFACE}/carrier")" == "0" ]]; do
      sleep 2
      i=$((i+1))
      if [[ $i -ge 6 ]]; then
        break
      fi
      echo -n "."
    done

    # if the link is not up we continue only if this is a
    # static connectin and no wifi config is present
    if [[ "$(cat "/sys/class/net/${IFACE}/carrier")" == "0" ]]; then
      echo -n " link down, "
      /sbin/ip link set "${IFACE}" down

      # if this is a DHCP setup we stop here. For static
      # connections we can still setup the ip but only if
      # no wifi setup follows
      if [[ "${MODE}" == "DHCP" ]] ||
         [[ -s /etc/config/wpa_supplicant.conf ]]; then
        exit 1
      fi
    else
      echo -n " link up, "
    fi
  ;;

  # start WPA Supplicant if this is a WiFi connection
  wlan*)
    # check if /boot/setupWiFi exists and contains the necessary
    # data to generate /etc/config/wpa_supplicant.conf automatically
    if [[ -s /boot/SetupWIFI ]]; then
      SETUPWIFI=/boot/SetupWIFI
    elif [[ -s /etc/config/SetupWIFI ]]; then
      SETUPWIFI=/etc/config/SetupWIFI
    fi

    if [[ -n "${SETUPWIFI}" ]]; then
      SSID=$(head -1 "${SETUPWIFI}" | dos2unix)
      PWD=$(tail -1 "${SETUPWIFI}" | dos2unix)
      if [[ -n "${SSID}" ]] && [[ -n "${PWD}" ]]; then
        cp /etc/config_templates/wpa_supplicant.conf /etc/config/wpa_supplicant.conf
        if /usr/sbin/wpa_passphrase "${SSID}" "${PWD}" >>/etc/config/wpa_supplicant.conf; then
          if [[ "$(dirname "${SETUPWIFI}")" == "/boot" ]]; then
            mount -o rw,remount /boot
            rm -f "${SETUPWIFI}"
            mount -o ro,remount /boot
          else
            rm -f "${SETUPWIFI}"
          fi
        fi
      fi
    fi

    # if /etc/config/wpa_supplicant.conf exists, bring up
    # the WiFi connection.
    if [[ -s /etc/config/wpa_supplicant.conf ]]; then
      # turn power save off and set link up
      /usr/sbin/iw dev "${IFACE}" set power_save off
      /sbin/ip link set "${IFACE}" up
      sleep 5
      /usr/sbin/rfkill unblock wlan
      /usr/sbin/wpa_supplicant -B w -i "${IFACE}" -c /etc/config/wpa_supplicant.conf -s
      echo -n " up, "
    else
      echo -n " no config, "
      # make sure that the wifi power is disabled
      # if not required
      /usr/sbin/iw dev "${IFACE}" set power_save on
      /usr/sbin/rfkill block wlan
      exit 1
    fi
  ;;
esac

# cleanup first
RESOLV_CONF=/tmp/resolv.conf.tmp
rm -f ${RESOLV_CONF}
rm -f /var/status/hasLink
rm -f /var/status/hasIP
rm -f /var/status/hasInternet

# make sure /var/status exists with correct permissions
if [[ ! -d /var/status ]]; then
  mkdir -p /var/status
  chown root:status /var/status
  chmod 2775 /var/status
fi

# setup the hostname
echo "${HOSTNAME}" >/etc/hostname
hostname "${HOSTNAME}"

# setup /etc/hosts
{
  echo "127.0.0.1 localhost"
  echo "127.0.1.1 ${HOSTNAME}"
  echo "::1 ip6-localhost ip6-loopback"
  echo "ff02::1 ip6-allnodes"
  echo "ff02::2 ip6-allrouters"
} > /etc/hosts

# restart syslogd to update hostname
/etc/init.d/S07logging restart 2>/dev/null >/dev/null

# check if we booting via nfs
if grep -q nfsroot /proc/cmdline ; then
   echo Running from nfs root. Skipping network configuration.

   # has IP  
   touch /var/status/hasLink
   touch /var/status/hasIP

   # check internet connection; use fix ip to google because no nameserver (nfs boot)
   /bin/checkInternet >/dev/null

   exit 0
fi

# make sure no other udhcpc is running
killall -q udhcpc

# if DHCP is enabled we run udhcpc
RET=0
case "${MODE}" in

  # if DHCP is enabled we "only" run udhcpc
  DHCP)
    echo -n "dhcp, "

    /sbin/udhcpc -b -t 20 -T 3 -S -x "hostname:${HOSTNAME}" -i "${IFACE}" -F "${HOSTNAME}" -V eQ3-CCU3 -s /bin/dhcp.script -p "/var/run/udhcpc_${IFACE}.pid" 2>/dev/null >/dev/null
    if [[ ! -f "/var/run/udhcpc_${IFACE}.pid" ]]; then
      killall -q checkDHCP
      /bin/checkDHCP "${IFACE}" &
    fi
  ;;

  # everything else means we are setting a static IP
  *)
    echo -n "static, "

    # use ifconfig so that broadcast address is correctly calculated
    /sbin/ifconfig "${IFACE}" "${IP}" netmask "${NETMASK}"

    # reset default gateway
    /sbin/ip route del default 2>/dev/null
    /sbin/ip route add default via "${GATEWAY}"

    # take care of resolv.conf
    if [[ -n "${NAMESERVER1}" ]]; then
      echo "nameserver ${NAMESERVER1}" >>${RESOLV_CONF}
    fi

    if [[ -n "${NAMESERVER2}" ]]; then
      echo "nameserver ${NAMESERVER2}" >>${RESOLV_CONF}
    fi

    # use /sbin/resolvconf to propagate DNS info to libc
    /sbin/resolvconf -a "${IFACE}" < ${RESOLV_CONF}
    rm -f ${RESOLV_CONF}

    # update CURRENT_XYZ in /etc/config/netconfig

    # update /etc/config/netconfig
    eq3configcmd netconfigcmd -i "${IP}" -g "${GATEWAY}" -n "${NETMASK}"

    if [[ -n "${NAMESERVER1}" ]]; then
      eq3configcmd netconfigcmd -d1 "${NAMESERVER1}"
    else
      eq3configcmd netconfigcmd -d1 ""
    fi

    if [[ -n "${NAMESERVER2}" ]]; then
      eq3configcmd netconfigcmd -d2 "${NAMESERVER2}"
    else
      eq3configcmd netconfigcmd -d2 ""
    fi

    touch /var/status/hasIP

    # we checked the link state already way earlier
    case "${IFACE}" in
      eth*)
        if [[ "$(cat "/sys/class/net/${IFACE}/carrier")" != "0" ]]; then
          touch /var/status/hasLink
        else
          RET=1
        fi
      ;;
      *)
        touch /var/status/hasLink
      ;;
    esac
  ;;

esac

# init the firewall only in case
# we are in normal startup mode
if [[ "${HM_MODE}" == "NORMAL" ]]; then
  # set firewall rules
  /bin/setfirewall.tcl
  echo -n "firewall, "
fi

# check internet connection
/bin/checkInternet >/dev/null
if [[ -f /var/status/hasInternet ]]; then
  echo -n "inet up, "
else
  echo -n "inet down, "
fi

IP=$(ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n')
echo -n "${IP}, "

exit ${RET}
